package com.tms.app.tms.ui;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.bigkoo.pickerview.TimePickerView;
import com.tms.app.tms.R;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.bean.ImgBean;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.bean.response.NodeTaskRes;
import com.tms.app.tms.ui.base.ui.AbsPhotoPickActivity;
import com.tms.app.tms.utils.MapUtil;
import com.tms.app.tms.utils.TimeUtil;
import com.tms.app.tms.utils.VerifyUtil;
import com.tms.app.tms.widget.CommonDialog;
import com.tms.app.tms.widget.MyDialogSelect;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.edu.zafu.camera.BdJson;
import cn.edu.zafu.camera.OrcTextUtil;
import cn.edu.zafu.camera.activity.CameraActivity;

import static com.tms.app.tms.utils.TimeUtil.getTimeYMD;

/**
 * Created by Administrator on 2017/10/28 0028.
 */

public class NodeTaskAC extends AbsPhotoPickActivity {
    @BindView(R.id.text_order_no)
    TextView textOrderNo;
    @BindView(R.id.line_photo_take_pick)
    LinearLayout linePhotoTakePick;

    @BindView(R.id.toolbar_left)
    TextView toolbarLeft;
    @BindView(R.id.toolbar_center)
    TextView toolbarCenter;
    @BindView(R.id.toolbar_right)
    TextView toolbarRight;
    @BindView(R.id.toolbar_text_right)
    TextView toolbarTextRight;
    @BindView(R.id.toolbar_search_text)
    EditText toolbarSearchText;
    @BindView(R.id.toolbar_search_button)
    Button toolbarSearchButton;
    @BindView(R.id.toolbar_search_parent)
    LinearLayout toolbarSearchParent;
    @BindView(R.id.button_send)
    Button buttonSend;
    @BindView(R.id.text_busi_type)
    TextView textBusiType;
    @BindView(R.id.text_order_no3)
    TextView textOrderNo3;
    @BindView(R.id.text_order_no4)
    TextView textOrderNo4;
    @BindView(R.id.text_order_no5)
    EditText textOrderNo5;
    @BindView(R.id.text_call_phone)
    TextView textCallPhone;
    @BindView(R.id.text_adress)
    TextView textAdress;
    @BindView(R.id.text_adress_map)
    TextView textAdressMap;
    @BindView(R.id.line_address)
    LinearLayout lineAddress;
    @BindView(R.id.text_order_no7)
    TextView textOrderNo7;
    @BindView(R.id.text_order_no8)
    EditText textOrderNo8;
    @BindView(R.id.text_scan)
    TextView textScan;
    @BindView(R.id.text_order_no9)
    EditText textOrderNo9;
    @BindView(R.id.line_part_1)
    LinearLayout linePart1;
    @BindView(R.id.img_1)
    ImageView img1;
    @BindView(R.id.photo_button_del_1)
    TextView photoButtonDel1;
    @BindView(R.id.img_parent_1)
    FrameLayout imgParent1;
    @BindView(R.id.img_2)
    ImageView img2;
    @BindView(R.id.photo_button_del_2)
    TextView photoButtonDel2;
    @BindView(R.id.img_parent_2)
    FrameLayout imgParent2;
    @BindView(R.id.img_3)
    ImageView img3;
    @BindView(R.id.photo_button_del_3)
    TextView photoButtonDel3;
    @BindView(R.id.img_parent_3)
    FrameLayout imgParent3;
    @BindView(R.id.img_4)
    ImageView img4;
    @BindView(R.id.photo_button_del_4)
    TextView photoButtonDel4;
    @BindView(R.id.img_parent_4)
    FrameLayout imgParent4;
    @BindView(R.id.text_photo_number)
    TextView textPhotoNumber;
    @BindView(R.id.img_net_error)
    ImageView imgNetError;
    @BindView(R.id.text_net_error)
    TextView textNetError;
    @BindView(R.id.net_errot_layout)
    LinearLayout netErrotLayout;
    @BindView(R.id.layout_people)
    LinearLayout layoutPeople;
    @BindView(R.id.layout_xianghao)
    LinearLayout layoutXianghao;
    @BindView(R.id.layout_fenghao)
    LinearLayout layoutFenghao;
    @BindView(R.id.text_order_no10)
    EditText textOrderNo10;
    private int stationExecId;
    String[] LBS = null;
    private String stationName;
    private String stationAddress = "";
    private String stationContent = "";
    private int dispatchId;
    private final String imgBasePath = "/sdcard/tms/bdorc/img/";
    NodeTaskeP nodeTaskeP = new NodeTaskeP();
    private int busiType;
    private String pelpon = "";
    private String mobile = "";
    private MyDialogSelect myDialogSelect;
    private int planIdShowType = -1;
    public List<ImgBean> imgBeanList = new ArrayList<>();
    List<String> locallist = new ArrayList<>();
    private String dialogTitle = "确定要保存吗";
    private String imgs = "";
    private String coNo = "";
    private String seaNo = "";
    private CommonDialog commFialog;
    private int doType = -1;
    private String tare="0";
    private String BD_token = "24.3c88e8965445ea74d90fa044ff8a8095.2592000.1519193981.282335-10364995";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        nodeTaskeP.setiView(this);
        setToolBarTitle("节点任务", -1, -1);
        stationExecId = getIntent().getIntExtra("stationExecId", 0);
        doType = getIntent().getIntExtra("doType", -1);
        nodeTaskeP.getNodeTask(token, stationExecId);
        initView();
    }

    private void initView() {
        planIdShowType = getIntent().getIntExtra("planIdShowType", -1);

//派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成4 挂起
        if (planIdShowType == 3 || planIdShowType == 13 ||
                planIdShowType == 4 || planIdShowType == 14) {
            buttonSend.setVisibility(View.GONE);
            textOrderNo5.setEnabled(false);
            textOrderNo8.setEnabled(false);
            textScan.setVisibility(View.INVISIBLE);
            textOrderNo9.setEnabled(false);
            textOrderNo10.setEnabled(false);
            try {
                findViewById(R.id.img_1).setEnabled(false);
                findViewById(R.id.photo_button_del_1).setVisibility(View.INVISIBLE);
                findViewById(R.id.img_2).setEnabled(false);
                findViewById(R.id.photo_button_del_2).setVisibility(View.INVISIBLE);
                findViewById(R.id.img_3).setEnabled(false);
                findViewById(R.id.photo_button_del_3).setVisibility(View.INVISIBLE);
                findViewById(R.id.img_4).setEnabled(false);
                findViewById(R.id.photo_button_del_4).setVisibility(View.INVISIBLE);
                findViewById(R.id.line_photo_take_pick).setEnabled(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (doType == 10) {
            layoutFenghao.setVisibility(View.GONE);
            layoutXianghao.setVisibility(View.GONE);
        }
    }

    @Override
    public void initLayout() {
        setContentView(R.layout.ac_layout_node_task);
    }

    @OnClick(R.id.line_address)
    public void goToWayBillInfo2() {
        if (stationAddress == null)
            return;
        if (LBS == null) {
            showMsg("坐标错误");
            return;
        }

        Intent intent = new Intent(this, MapAc.class);
        intent.putExtra("title", stationName);
        intent.putExtra("adress", stationAddress);
        intent.putExtra("content", stationContent);
        intent.putExtra("lat", LBS[1]);
        intent.putExtra("lon", LBS[0]);
        startActivity(intent);
        showLoadingDialog();
        if (true)
            return;
        if (!MapUtil.isAvilible(this, "com.autonavi.minimap")) {
            showMsg("您的手机未安装高德地图");
            return;
        }

        intent = new Intent("android.intent.action.VIEW",//31.192612,121.420287
                Uri.parse("androidamap://viewMap?sourceApplication=appname&poiname=湘江大厦&lat=31.192612&lon=121.420287&dev=0"));
        intent.setPackage("com.autonavi.minimap");
        startActivity(intent);
    }

    @OnClick({R.id.text_order_no, R.id.text_call_phone, R.id.layout_people,
            R.id.line_address, R.id.text_adress_map,
            R.id.text_scan, R.id.button_send})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent intent = null;
        switch (view.getId()) {

            case R.id.text_order_no:
                intent = new Intent(this, WayBillInfoAC.class);
                intent.putExtra("dispatchId", dispatchId);
                intent.putExtra("planIdShowType", planIdShowType);
                intent.putExtra("type", busiType);
                startActivityForResult(intent, 0x123);
                break;
            case R.id.line_address:
            case R.id.text_adress_map:
                break;
            case R.id.text_scan:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//小写的mm表示的是分钟
                intent = new Intent(this, CameraActivity.class);
                intent.putExtra("path", imgBasePath);
                intent.putExtra("name", sdf.format(new Date()) + ".jpg");
                intent.putExtra("type", "idcardFront");
                startActivityForResult(intent, 100);
                break;
            case R.id.text_call_phone:
            case R.id.layout_people:
                myDialogSelect = new MyDialogSelect(this, this, pelpon, mobile);
                myDialogSelect.show();
                break;
            case R.id.dialog_button_1:
            case R.id.dialog_photo_button_1:
                if (myDialogSelect != null)
                    myDialogSelect.close();
                if (myDialogPhoto != null)
                    myDialogPhoto.close();
                break;
            case R.id.dialog_button_2:
                myDialogSelect.close();
                String mobile = textOrderNo5.getText().toString();
                callPhone(VerifyUtil.getMobileNumber(mobile));
                break;
            case R.id.button_send:
                saveNodeTask();
                break;
            case R.id.dialog_photo_button_2://对话框确认按钮
                nodeTaskeP.stationDo(token, stationExecId, coNo, seaNo, locallist, imgs,tare);
                commFialog.close();
                break;

        }
    }

    public void pickTime(final TextView textView) {
        //时间选择器
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(1990, 0, 1);
        // endDate.set(2020,11,31);

        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                textView.setText(getTimeYMD(date));
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                // .setTitleText("Title")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setTitleBgColor(0xFF0081C2)//标题背景颜色 Night mode
                .setBgColor(0xFF0081C2)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                // .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .setLabel("年", "月", "日", "时", "分", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    @Override
    public void delSerImg(int index) {
        imgBeanList.get(index).setImgSrc(null);
    }


    private void saveNodeTask() {
        coNo = textOrderNo8.getText().toString();
        seaNo = textOrderNo9.getText().toString();
        tare = textOrderNo10.getText().toString();
        if (doType != 10 && StringUtil.isEmpty(coNo)) {
            showMsg("请填写箱号");
            return;
        }
        if (doType != 10 && StringUtil.isEmpty(seaNo)) {
            showMsg("请填写封号");
            return;
        }
        locallist.clear();
        for (View view : imgSelectList.keySet()) {
            if (imgSelectList.get(view) != null && !imgSelectList.get(view).equals("-1")) {
                locallist.add(imgSelectList.get(view));
            }
        }
        StringBuffer sb = new StringBuffer();
        for (ImgBean imgBean : imgBeanList) {
            if (imgBean.getImgSrc() != null
                    && imgBean.getImgSrc().length() > 1 && !imgBean.getImgSrc().equals("-1")) {

                sb.append(imgBean.getImgSrc()).append(",");
            }
        }
        if (sb.length() > 2) {
            imgs = sb.subSequence(0, sb.length() - 1).toString();
        }
        commFialog = CommonDialog.getInstance(this, this, dialogTitle);
        commFialog.show();
        // nodeTaskeP.stationDo(token, stationExecId, coNo, seaNo, locallist, imgs);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void doNode(String json) {
        BaseResponse baseResponse = gson.fromJson(json, BaseResponse.class);
        if (baseResponse == null || baseResponse.getCode() == -1) {
            BdJson bsjson = gson.fromJson(json, BdJson.class);
            if (bsjson.getWords_result() != null && bsjson.getWords_result().size() > 0) {
                String resultDb = bsjson.getWords_result().get(0).getWords();
                resultDb = OrcTextUtil.formatOrcText(resultDb);
                if (OrcTextUtil.checkTextRight(resultDb)) {
                    textOrderNo8.setText(resultDb);
                    textOrderNo8.setTextColor(getResources().getColor(R.color.color_font_black));
                } else {
                    textOrderNo8.setText(OrcTextUtil.getGussOrcText(resultDb));
                    textOrderNo8.setTextColor(getResources().getColor(R.color.red));
                }
            } else {
                //showMsg(bsjson.getError_msg());
                showMsg("识别失败");
            }

        }
        if (baseResponse.getCode() == 200) {
            //  nodeTaskeP.uploadGps(token);
            setResult(Constant.fineshNodeTask);
            finish();
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bandData(NodeTaskRes nodeTaskRes) {
        if (nodeTaskRes.getCode() == 200) {
            if (nodeTaskRes.getData().getWaybillNo() == null)
                textOrderNo.setText("运单号：");
            else
                textOrderNo.setText("运单号：" + nodeTaskRes.getData().getWaybillNo());
            switch (nodeTaskRes.getData().getBusiType()) {
                case 0:
                    textBusiType.setText("业务类型：" + "进口");
                    break;
                case 1:
                    textBusiType.setText("业务类型：" + "出口");
                    break;
                case 2:
                    textBusiType.setText("业务类型：" + "公路");
                    break;
                default:
                    textBusiType.setText("业务类型：" + "");
            }
            pelpon = nodeTaskRes.getData().getDispatchUserName();
            mobile = nodeTaskRes.getData().getDispatchUserPhone();
            //  textBusiType.setText("业务类型：" + nodeTaskRes.getData().getBusiType());
            textOrderNo3.setText("箱型：" + nodeTaskRes.getData().getContainerTypeName());
            if (nodeTaskRes.getData().getStationName() != null)
                textOrderNo4.setText("门点：" + nodeTaskRes.getData().getStationName());
            textOrderNo5.setText(nodeTaskRes.getData().getDispatchUserName() + "   " + nodeTaskRes.getData().getDispatchUserPhone());
            if (pelpon == null || mobile == null)
                textOrderNo5.setText("");
            if (nodeTaskRes.getData().getStationAddress() != null)
                textAdress.setText("地址：" + nodeTaskRes.getData().getStationAddress());
            textOrderNo7.setText(" 做箱时间：" + TimeUtil.getTimeFormat(nodeTaskRes.getData().getExecTime()));
            textOrderNo8.setText(nodeTaskRes.getData().getContainerNo());
            textOrderNo9.setText(nodeTaskRes.getData().getSealNo());
            textOrderNo10.setText(nodeTaskRes.getData().getTare());
            LBS = nodeTaskRes.getData().getStationLBS().split(",");
            stationName = nodeTaskRes.getData().getStationName();
            stationAddress = nodeTaskRes.getData().getStationAddress();
            stationContent = nodeTaskRes.getData().getStationContactPerson()
                    + " "
                    + nodeTaskRes.getData().getDispatchUserPhone();
            dispatchId = nodeTaskRes.getData().getDispatchId();
            busiType = nodeTaskRes.getData().getBusiType();
            imgBeanList = nodeTaskRes.getData().getNodeImgList();
            for (int i = 0; i < nodeTaskRes.getData().getNodeImgList().size(); i++) {
                if (!StringUtil.isEmpty(nodeTaskRes.getData().getNodeImgList().get(i).getImgSrc()))
                    imgServerList.put(imgViewList.get(i), nodeTaskRes.getData().getNodeImgList().get(i).getImgSrc());
            }
            loadPickPhoto();
            if (nodeTaskRes.getData().getStationExecStatus() != 2) {
                dialogTitle = "确定要保存吗？";
                buttonSend.setText("保存");

            } else {
                dialogTitle = "确定要变更保存吗？";
                buttonSend.setText("变更保存");
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("TAG", "onActivityResult");
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();
                String path = extras.getString("path");
                String type = extras.getString("type");
                //   Toast.makeText(getApplicationContext(), "path:" + path + " type:" + type, Toast.LENGTH_LONG).show();
                nodeTaskeP.uploadAndRecognize(0, path);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
